package com.dtkavin.threads.syn;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by john on 10/4/16.
 * synchronized -使用- wait, notify
 * lock -使用- condition
 */
public class ConditionDemo {
    public static void main(String[] args) {
        final ShareData data = new ShareData();
        new Thread(new Runnable() {
            public void run() {
                while (true) {
                    data.print1();
                }
            }
        }).start();

        new Thread(new Runnable() {
            public void run() {
                while (true) {
                    data.print2();
                }
            }
        }).start();
    }

    static class ShareData {
        boolean run1 = true;
        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();

        public void print1() {
            lock.lock();
            try {
                while (!run1) {
                    try {
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                for (int i = 0; i < 5; i++) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("pirnt 1 : " + Thread.currentThread().getName());
                }
                run1 = false;
                condition.signal();
            } finally {
                lock.unlock();
            }
        }

        public void print2() {
            lock.lock();
            try {
                while (run1) {
                    try {
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                for (int i = 0; i < 2; i++) {
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("print2 : " + Thread.currentThread().getName());
                }
                run1 = true;
                condition.signal();
            } finally {
                lock.unlock();
            }
        }
    }
}
